<template>
  <div class="authority">
    <div class="gva-search-box">
      <el-form ref="searchForm" :inline="true">
        <el-form-item label="标题">
          <el-input v-model="searchInfo.title" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">
            查询
          </el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box unit">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="addUnit">新增消息</el-button>
      </div>
      <div class="ant-alert-info">
        <el-popover placement="left-start" :width="350" trigger="click" transition='el-zoom-in-left'>
          <div class="pop-content">
            <div class="pop-title">自定义列</div>
            <div class="check-list">
              <el-checkbox-group v-model="checkedColumns" @change="handleColumnsChange">
                <el-checkbox v-for="column in columns" :value="column" :label="column"></el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
          <template #reference>
            <div class="anticon">
              <el-icon size="16" color="#1890ff">
                <Setting />
              </el-icon>
              <div style="margin-left: 2px;">自定义列</div>
            </div>
          </template>
        </el-popover>
      </div>
      <el-table :data="tableData" row-key="id">
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column align="left" label="标题" prop="title" show-overflow-tooltip v-if="checkedColumns.includes('标题')"></el-table-column>
        <el-table-column align="left" label="是否发布" prop="publishStatus" v-if="checkedColumns.includes('是否发布')">
          <template #default="scope">
            <el-tag type="primary" v-if="scope.row.publishStatus == 1">已发布</el-tag>
            <el-tag type="danger" v-if="scope.row.publishStatus == 2">未发布</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="left" label="是否公开" prop="public" v-if="checkedColumns.includes('是否公开')">
          <template #default="scope">
            <el-tag type="primary" v-if="scope.row.public == 1">已公开</el-tag>
            <el-tag type="danger" v-if="scope.row.public == 2">未公开</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="left" label="时间" prop="publishTime"
          v-if="checkedColumns.includes('时间')"></el-table-column>
        <el-table-column align="left" label="操作人" prop="createUser"
          v-if="checkedColumns.includes('操作人')"></el-table-column>
        <el-table-column align="left" label="消息类别" v-if="checkedColumns.includes('消息类别')">
          <template #default="scope">
            {{ scope.row.type == 1 ? '工作动态' : '政策法规' }}
          </template>
        </el-table-column>
        <el-table-column align="left" fixed="right" label="操作" min-width="160" v-if="checkedColumns.includes('操作')">
          <template #default="scope">
            <el-button type="primary" link icon="edit" @click="editUnit(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" link icon="delete" @click="delUnit(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination v-model:current-page="page" :page-size="pageSize" :total="total" layout="prev, pager, next"
          @current-change="handleCurrentChange" />
      </div>
    </div>
    <el-drawer v-model="dialogFormVisible" :size="1000" :before-close="handleClose" :show-close="false">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">{{ dialogTitle }}</span>
          <div>
            <el-button @click="closeDialog">取消</el-button>
            <el-button type="primary" @click="enterDialog">确定</el-button>
          </div>
        </div>
      </template>
      <el-form v-if="dialogFormVisible" ref="yyglForm" label-width="150" :model="form" :rules="rules">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="消息类别" prop="type">
          <el-radio-group v-model="form.type" class="ml-4">
            <el-radio :value="1" size="large">工作动态</el-radio>
            <el-radio :value="2" size="large">政策法规</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发布时间">
          <el-date-picker v-model="form.publishTime" value-format="YYYY-MM-DD hh:mm:ss" type="datetime"
            placeholder="请选择" />
        </el-form-item>
        <el-form-item label="主图">
          <el-upload v-model:file-list="fileList" :action="adminUrl" :on-success="uploadSuccess" :headers="headerOdj"
            list-type="picture-card" :on-preview="handlePicturePreview">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="内容" prop="content" style="align-items: normal;">
          <RichEdit v-model="form.content" />
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>
<script setup>
import {
  getXxList,
  deleteXx,
  createXx,
  updateXx
} from '@/api/xitongpeizhi'

import { reactive, ref, onMounted } from 'vue'
import { useAppStore } from "@/pinia";
import { useUserStore } from '@/pinia/modules/user'
import { ElMessage, ElMessageBox, useFormItem } from 'element-plus'
import RichEdit from '@/components/richtext/rich-edit.vue'

// 通过该函数，可以获取组件当前所在的表单项formItem
const { formItem } = useFormItem()

defineOptions({
  name: 'Yygl'
})

const appStore = useAppStore()
const form = ref({
  title: '',
  content: '',
  type: 1,
  publishTime: '',
  picture: ''
})

const searchInfo = ref({
  title: ''
})
let dialogVisible = ref(false)
let dialogImageUrl = ref()

//图片预览
const handlePicturePreview = (file, files) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true
}

const userStore = useUserStore()
const headerOdj = ref({ token: userStore.token })
const adminUrl = ref('')
adminUrl.value = import.meta.env.VITE_BASE_PATH + '/file/upload'
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const dialogFormVisible = ref(false)
let validateImage = (rule, value, callback) => {
  if (!form.value.ico) {
    callback(new Error('请上传图片'))
  } else {
    callback()
  }
}
const rules = reactive({
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
  type: [{ required: true, message: '请选择消息类别', trigger: 'change' }]
})

const yyglForm = ref(null)

const initForm = () => {
  yyglForm.value.resetFields()
  form.value = {
    title: '',
    content: '',
    type: 1,
    publishTime: '',
    picture: ''
  }
  fileList.value = []
}

const checkedColumns = ref(['序号', '标题', '是否发布', '是否公开', '时间', '操作人', '消息类别', '操作'])

if (localStorage.getItem('columnData') && JSON.parse(localStorage.getItem('columnData')).xxfb) {
  checkedColumns.value = JSON.parse(localStorage.getItem('columnData')).xxfb
}
const columns = ref(['序号', '标题', '是否发布', '是否公开', '时间', '操作人', '消息类别', '操作'])
const handleColumnsChange = (val) => {
  let obj = {

  }
  if (localStorage.getItem('columnData')) {
    obj = JSON.parse(localStorage.getItem('columnData'))
  }
  obj.xxfb = val
  localStorage.setItem('columnData', JSON.stringify(obj))
}
const isEdit = ref(false)
const dialogTitle = ref('新增消息')
const addUnit = () => {
  dialogTitle.value = '新增消息'
  isEdit.value = false
  dialogFormVisible.value = true
}
const closeDialog = () => {
  initForm()
  dialogFormVisible.value = false
}

const handleClose = (done) => {
  initForm()
  done()
}
const handleUserClose = (done) => {
  initUserForm()
  done()
}
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}
const tableData = ref([])
// 查询
const getTableData = async () => {
  const res = await getXxList({
    pageNumber: page.value,
    pageSize: pageSize.value,
    ...searchInfo.value
  })
  if (res.code == 200) {
    tableData.value = res.result.data
    total.value = res.result.total
  }
}
getTableData()

onMounted(() => {

})

const enterDialog = async () => {
  yyglForm.value.validate(async (valid) => {
    if (valid) {
      let res
      if (isEdit.value) {
        res = await updateXx(form.value)
      } else {
        res = await createXx(form.value)
      }
      if (res.code == 200) {
        ElMessage({
          type: 'success',
          message: isEdit.value ? '编辑成功' : '添加成功!'
        })
        getTableData()
      }
      initForm()
      dialogFormVisible.value = false
    }
  })
}

const delUnit = (row) => {
  ElMessageBox.confirm(
    '确认删除?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    const res = await deleteXx(row.id)
    if (res.code === 200) {
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      getTableData()
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}

const editUnit = async (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑消息'
  form.value = JSON.parse(JSON.stringify(row))
  form.value.messageId = form.value.id
  if (form.value.picture) {
    fileList.value = [{
      name: '1',
      url: form.value.picture
    }]
  }
  dialogFormVisible.value = true
}

const onSubmit = () => {
  page.value = 1
  getTableData()
}

const onReset = () => {
  searchInfo.value = {
    title: ''
  }
  getTableData()
}

const fileList = ref([])
const handleRemove = (file) => {
  fileList.value = []
  form.value.ico = ''
}
const uploadSuccess = (res) => {
  if (res.code != 200) {
    ElMessage({
      type: 'warning',
      message: res.message
    })
    fileList.value.pop()
    return
  }
  form.value.picture = res.result
  //yyglForm.value.validateField('ico')
}

</script>

<style lang="scss">
.flex {
  .area {
    flex: 2;
    background-color: #fff;
    margin: 0.5rem 20px 0.5rem 0;
  }

  .unit {
    flex: 4;
  }
}

.ant-alert-info {
  display: flex;
  justify-content: end;
  align-items: center;
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
  color: #1890ff;
  padding: 5px;

  .anticon {
    display: flex;
    align-items: center;
    cursor: pointer;
  }
}

.pop-content {
  .pop-title {
    font-weight: bold;
    padding-bottom: 4px;
    border-bottom: 1px solid rgba(5, 5, 5, 0.06);
  }

  .el-checkbox-group {
    font-size: 0;
    line-height: 0;
    display: flex;
    flex-wrap: wrap;
  }
}
</style>
